package com.eastcom.groovy.task.taskdirector.file.txt

import java.awt.TexturePaintContext.Int;
import java.sql.Date;
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javassist.bytecode.stackmap.BasicBlock.Catch;

import com.eastcom.groovy.tools.common.JmsJndiConfig
import com.eastcom.groovy.tools.common.MQCommunication
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.db.JdbcUtil;
import com.eastcom.groovy.tools.file.FtpUtils;
import com.eastcom.groovy.provider.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
class SimpleTxtFileTaskDirector {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String[] ftpLocalPath =
	[
		"/home/cache/feisida"
	]
	final String fileNameRgex = "udpping-(\\d+)-(\\d+)\\.csv"
	final String ftpFileEnCode = "GBK"
	final long fileLimit = 2400000
	final String dstdbBean = "oracle_86_nhm"
	final String fileNameTimeFormat = "yyyyMMddHHmm"
	final String[] regex =
	[
		"[^,\\n\\u4E00-\\u9FFFa-zA-Z_]+,([^,]+),([^,]+),([^,]+),([^,\\n]+)"
	]
	final int[][] groupId =
	[
		[1,2,3,4]
	]
	final int parseLineNumOnce = 1
	final String objectId = "TEST"
	final String eventId = "TEST"
	final String insertSql = "insert into NHM_GAMES_TCPMASS(TIME_STAMP,GAME_NAME,PACKET_LOSS,DELAY_TIME,JITTER) values(?,?,?,?,?)"
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static List<String> dstFieldList = new ArrayList()
	static List<Integer> dstFieldTypeList = new ArrayList()
	static int[] sqlTypes
	List<List<String>> parseResultList = new ArrayList()
	static Log logger = LogFactory.getLog(SimpleTxtFileTaskDirector.class)


	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){
		//		String dstdbBean,List<String> dstFieldList,List<String> dstFieldTypeList,int[] sqlTypes,String insertSql,boolean isDomain
		DbEngine.doDbInit(dstdbBean, dstFieldList, dstFieldTypeList, insertSql, true)
		sqlTypes = new int[dstFieldTypeList.size()]
		for(int i = 0; i < dstFieldTypeList.size(); i++){
			sqlTypes[i] = dstFieldTypeList.get(i)
		}

		println sqlTypes
	}

	public boolean doJob(String jobId){
		doParseFile()
		logger.debug("SimpleTxtFileTaskDirector doParseFile任务完成！")
	}




	private boolean doParseFile(){
		try{
			Calendar fileTime = Calendar.getInstance();
			Calendar fileLimitTime = Calendar.getInstance();
			fileLimitTime.setTimeInMillis(new java.util.Date().getTime() - fileLimit);
			for(int t = 0; t < ftpLocalPath.length; t++){
				File dirs = new File(ftpLocalPath[t])
				File[] dirFile = dirs.listFiles(new FilenameFilter() {
							@Override
							public boolean accept(File dir, String name) {
								// TODO 自动生成的方法存根
								if(name.matches(fileNameRgex)){
									return true;
								}
								return false;
							}
						});
				for(File f: dirFile){
					long time = f.lastModified();
					fileTime.setTimeInMillis(time);
					if(fileTime.before(fileLimitTime)){
						continue;
					}
					String fileNameTime = null;

					String fileName = f.getName()
					println fileName
					Pattern pat = Pattern.compile(fileNameRgex);

					Matcher mat = pat.matcher(fileName);
					if(mat.find()){
						fileNameTime = mat.group(1)+mat.group(2)
						println fileNameTime
					}else{
						continue
					}
					BufferedReader reader = null;


					try {
						reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), ftpFileEnCode));
					} catch (Exception e) {
						e.printStackTrace()
					}
					for(int index = 0; index < regex.length; index++){
						String rg = regex[index]
						int[] gd = groupId[index]
						StringBuilder context = new StringBuilder();
						pat = Pattern.compile(rg);
						String line = null;
						boolean isFileEnd = false;
						int counts = 0
						boolean rs = false
						while(true){
							if(parseResultList.size() >= 15000){
								doInsertResult()
							}
							for(int i = 0; i < parseLineNumOnce; i++){
								try {
									line = reader.readLine()
									logger.debug("line="+line)
									if(line == null){
										isFileEnd = true
										break
									}
								} catch (Exception e) {
									e.printStackTrace()
								}
								context.append(line+"\n")
							}
							println context.toString()
							mat = pat.matcher(context.toString());
							rs = mat.find();
							if(rs){
								context = new StringBuilder();
								List<String> valueList = new ArrayList<String>();
								valueList.add(fileNameTime)
								for(int g : gd){
									String ct = mat.group(g)
									valueList.add(ct);
								}
								parseResultList.add(valueList)
							}else{
								logger.debug("不匹配！"+regex+"-------"+context.toString());
							}
							if(isFileEnd){
								logger.debug("文件已经读完！");
								doInsertResult()
								break;
							}
						}
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private boolean doInsertResult(){
		try{
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
			for(List<String> raw: parseResultList){
				Object[] param = new Object[raw.size()]
				for(int i = 0; i < raw.size(); i++){
					print raw.get(i)+"--"+sqlTypes[i]+"\t"
					String value = raw.get(i)
					value = specailWork(i, value)
					try {
						switch(sqlTypes[i]){
							case Types.INTEGER:
								param[i] = Integer.valueOf(value)
								break
							case Types.FLOAT:
							case Types.DOUBLE:
								param[i] = Double.valueOf(value)
								break
							case Types.DECIMAL:
							case Types.NUMERIC:
								param[i] = BigDecimal.valueOf(Double.valueOf(value))
								break
							case Types.TIMESTAMP:
								java.util.Date date = new SimpleDateFormat(fileNameTimeFormat).parse(value)
								logger.debug(date)
								param[i] = new Timestamp(date.getTime())
								break
							case Types.DATE:
								java.util.Date date = new SimpleDateFormat(fileNameTimeFormat).parse(value)
								logger.debug(date)
								param[i] = new Date(date.getTime())
								break
							case Types.VARCHAR:
							case Types.NVARCHAR:
								param[i] = value
								break
							case Types.OTHER:
								param[i] = value
								break;
							default:
								param[i] = null
								logger.warn("入库数据库字段无法识别！使用Null插入！")
								break;
						}
					} catch (Exception e) {
						e.printStackTrace()
						logger.error(e.getMessage())
						param[i]=null
					}
				}
				try{
					dbEngine.getJdbcUtil().update(insertSql, param, sqlTypes)
				}catch(Exception e){
					e.printStackTrace()
					logger.error(e.getMessage())
				}
				println ""
			}
			parseResultList.clear()
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}
	
	private Object specailWork(int index,String value){
		if(value == null){
			return null
		}else if(value.equalsIgnoreCase("NULL")){
			return "0"
		}
		if(index == 1){
			if(value.contains("TCP") || value.contains("UDP")){
				value = value.substring(0, value.length() - 3)
				return value
			}
		}
		return value
	}
}